﻿using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Ly.EBussiness.EntityFrameworkCore.Auth.User;
using Microsoft.IdentityModel.Tokens;

namespace Ly.EBussiness.EntityFrameworkCore.Auth;

public class JwtHelp
{
    private const string SecurityKey = "ZLhBUFIl0OGwUVpM6afg+HsdbgbRHQlv";
    private const string Issuer = "server";
    private const string Audience = "client007";
    public static TokenValidationParameters CreateTokenValidationParameters()
    {
        return new TokenValidationParameters
        {
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(SecurityKey)), // 加密解密Token的密钥
            // 是否验证发布者
            ValidateIssuer = true,
            // 发布者名称
            ValidIssuer = Issuer,
            // 是否验证订阅者
            // 订阅者名称
            ValidateAudience = true,
            ValidAudience = Audience,

            // 是否验证令牌有效期
            ValidateLifetime = true,
            // 每次颁发令牌，令牌有效时间
            ClockSkew = TimeSpan.FromMinutes(120)
        };
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="userId"></param>
    /// <param name="userName"></param>
    /// <param name="role"></param>
    /// <returns></returns>
    public static string getToken(string userId,string userName,string role = Role.CustomUser)
    {
        // if (userId == "124422113830") role = Role.Admin;
        // 定义用户信息
        var claims = new Claim[]
        {
            new(CustomClaimTypes.UserId, userId),
            new(CustomClaimTypes.UserName, userName),
            new(CustomClaimTypes.Role, role),
        };
        // 和 Startup 中的配置一致
        SymmetricSecurityKey key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(SecurityKey));
        JwtSecurityToken token = new JwtSecurityToken(
            issuer: Issuer,
            audience: Audience,
            claims: claims,
            notBefore: DateTime.Now,
            expires: DateTime.Now.AddDays(30), // todo 注意这里上线后需要更改
            signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256)
        );
        var jwtToken = new JwtSecurityTokenHandler().WriteToken(token);
        return jwtToken;
    }
}